package com.levy.contronller.javaWeb.shiroTest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * Created by 郭利伟 on 2017.08.27.
 */
public class shiroTest {
    public static void main(String[] args) {
        //1、获取SecurityManager工厂，此处使用Ini配置文件初始化SecurityManager
        IniSecurityManagerFactory ini = new IniSecurityManagerFactory("classpath:auth.ini");
        SecurityManager sm = ini.getInstance();
        //2、得到SecurityManager实例 并绑定给SecurityUtils
        SecurityUtils.setSecurityManager(sm);
        //以下3行代码为  将redis数据源加入到Shiro中
//        DefaultSecurityManager  dm = (DefaultSecurityManager)sm;
//        Collection<Realm> realms = dm.getRealms();
//        RedisRealm rr = new RedisRealm();
//        realms.add(rr);

        //3、得到Subject及创建用户名/密码身份验证Token（即用户身份/凭证）
        Subject user = SecurityUtils.getSubject();
        if (!user.isAuthenticated()){
            UsernamePasswordToken u = new UsernamePasswordToken("zhangsan","1234");
            try {
                user.login(u);
                System.out.println("登陆成功，当前用户为---"+user.getPrincipal());
            }catch (AuthenticationException e){
                System.out.println("登陆失败"+e.getMessage());
            }
        }

        if (user.hasRole("admin")){
            System.out.println("当前用户角色为--管理员");
        }else{
            System.out.println("----role--------");
        }
        if (user.isPermitted("livingroom:walk:A")){
            System.out.println("可以在卧室中行走");
        }else {
            System.out.println("----permimt--------");
        }



    }


}
